using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using TVT.UI.Helpers;
using System.Collections.Generic;
using TVT.Common.Exceptions;
using TVT.UI.EventArguments;
using TVT.Common.Helpers;
using TVT.BizLayer.Entities;
using System.IO;


namespace TVT.UI.UserControls
{
    public partial class ListComments : System.Web.UI.UserControl
    {
        public event EventHandler OnContactUser = null;

        public void ContactUser(UserEventArgs args)
        {
            if (OnContactUser != null)
            {
                OnContactUser(this, args);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ViewState["SortExpression"] = "LastName DESC";
                gvComments.PageSize = Int32.Parse(ConfigurationManager.AppSettings[WellKnownKeys.GridViewsPageSizeKey]);
                try
                {
                    BindData();                    
                }
                catch (FunctionalException ex)
                {
                    lblTransactionResultMessage.Text = ex.Message;
                }
            }
        }

        private void BindData()
        {
             List<Comment> comments;
             User logUser = User.Find((Guid)Membership.GetUser().ProviderUserKey);
             List<string> rolesOk = new List<string>();
             foreach (string r in Roles.GetAllRoles())
             {
                 if (r != WellKnownKeys.AdministratorRolKey)
                     rolesOk.Add(r);
             }

             comments = logUser.Comments;

             if (comments.Count == 0)
             {
                 lblTransactionResultMessage.Text = Resources.NoResultsFound;
                 lblTransactionResultMessage.Visible = true;
             }
             else
             {
                 lblTransactionResultMessage.Visible = false;
                 pnlSearchCommentsResults.Visible = true;
             }

             gvComments.DataSource = comments;
             ViewState["SortableListComments"] = comments;
            gvComments.DataBind();
        }

        protected void gvComments_PageIndexChanging(Object sender, GridViewPageEventArgs e)
        {            
            gvComments.PageIndex = e.NewPageIndex;
            if (gvComments.EditIndex != -1)
            {      
                e.Cancel = true;             
                int newPageNumber = e.NewPageIndex + 1;                
            }
            else
            {
                DataView dataView = new DataView(GetDataTableFromCommentsList((List<Comment>)ViewState["SortableListComments"]));

                dataView.Sort = ViewState["SortExpression"].ToString();
                gvComments.DataSource = dataView;
                gvComments.DataBind();
            }

        }

        protected void OnSortingGvComments(object sender, GridViewSortEventArgs e)
        {
            string sort = " DESC";

            if (ViewState["sortDirection"] == null)
                ViewState["sortDirection"] = SortDirection.Ascending;
            else
            {
                if ((SortDirection)ViewState["sortDirection"] == SortDirection.Ascending)
                {
                    ViewState["sortDirection"] = SortDirection.Descending;
                    sort = " DESC";
                }
                else
                {
                    ViewState["sortDirection"] = SortDirection.Ascending;
                    sort = " ASC";
                }
            }

            List<Comment> comments = (List<Comment>)ViewState["SortableListComments"];
            DataTable dataTable = GetDataTableFromCommentsList(comments);

            if (dataTable != null)
            {
                DataView dataView = new DataView(dataTable);

                dataView.Sort = e.SortExpression + sort;
                ViewState["SortExpression"] = e.SortExpression + sort;
                gvComments.DataSource = dataView;
                gvComments.DataBind();
            }
        }        

        private DataTable GetDataTableFromCommentsList(List<Comment> comments)
        {
            DataTable dataTable = new DataTable();

            dataTable.Columns.Add("Id");
            dataTable.Columns["Id"].DataType = System.Type.GetType("System.Int32");
            
            dataTable.Columns.Add("UserName");
            dataTable.Columns["UserName"].DataType = System.Type.GetType("System.String");

            dataTable.Columns.Add("Comment");
            dataTable.Columns["Comment"].DataType = System.Type.GetType("System.String");

            DataRow dataRow;

            foreach (Comment comment in comments)
            {
                dataRow = dataTable.NewRow();

                dataRow["Id"] = comment.Id;
                dataRow["UserName"] = (comment.UserFrom).UserName;
                dataRow["Comment"] = comment.Text;

                dataTable.Rows.Add(dataRow);
            }

            return dataTable;
        }

        protected void gvComments_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            StylesApplier stylesApplier = new StylesApplier();
            int id = 0;
            try
            {
                stylesApplier.GridViewStyle(e.Row);

                Comment comment = null;
                comment = ((Comment)(e.Row.DataItem));

                if ((comment != null) && (comment.Id != 0))
                {
                    id = comment.Id;
                    comment = ((Comment)(e.Row.DataItem));

                    Image imgUser = (Image)e.Row.FindControl("imgUser");
                    String imgUrl = ConfigurationManager.AppSettings[WellKnownKeys.TemporaryFilesPathKey].ToString() + comment.UserFrom.UserName + ".jpg";
                    String fullPath = imgUrl.Replace("~", AppDomain.CurrentDomain.BaseDirectory);
                    if (File.Exists(fullPath))
                        imgUser.ImageUrl = imgUrl;

                    Label lblUserName = (Label)e.Row.FindControl("lblUserName");
                    lblUserName.Text = comment.UserFrom.UserName;

                    Label lblComment = (Label)e.Row.FindControl("lblComment");
                    lblComment.Text = comment.Text;
                   
                }
            }

            catch (Exception)
            {
                
            }

            if (id != 0)
            {
                ImageButton lbtnDelete = (ImageButton)e.Row.FindControl("lbtnDelete");
                lbtnDelete.CommandArgument = id.ToString();
            }
        }

        protected void gvComments_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string id = e.CommandArgument.ToString();

            if (e.CommandName == "DeleteComment")
            {
                lblTransactionResultMessage.Visible = true;
                
                try
                {
                    Guid userId = new Guid(id);
                    Guid usserIdLogged = (Guid)Membership.GetUser().ProviderUserKey;

                    BindData();
                   
                }
                catch (FunctionalException ex)
                {
                    lblTransactionResultMessage.Text = ex.Message;
                }
            }
        }
    }
}